package com.bwie.S;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class MonopolyGame {
    private static final int PLAYER_COUNT = 4; // 玩家数量
    private static final Semaphore[] semaphores = new Semaphore[PLAYER_COUNT];

    public static void main(String[] args) {
        // 初始化信号量数组
        for (int i = 0; i < PLAYER_COUNT; i++) {
            semaphores[i] = new Semaphore(1);
        }

        // 初始化时，仅允许第一个玩家行动
        for (int i = 1; i < PLAYER_COUNT; i++) {
            semaphores[i].acquireUninterruptibly();
        }

        // 创建并启动玩家线程
        for (int i = 0; i < PLAYER_COUNT; i++) {
            final int playerId = i;
            new Thread(() -> {
                while (true) { // 游戏循环
                    semaphores[playerId].acquireUninterruptibly(); // 获取许可
                    if (Thread.currentThread().isInterrupted()) break; // 游戏结束条件

                    System.out.println("选手 " + playerId + " 正在掷骰子。");
                    int steps = rollDice();
                    System.out.println("选手 " + playerId + " 移动 " + steps + "步");

                    // 模拟一些处理时间
                    try {
                        Thread.sleep(1000); // 模拟玩家执行动作的时间
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt(); // 保证线程中断状态
                    }

                    // 将控制权传递给下一个玩家
                    int nextPlayer = (playerId + 1) % PLAYER_COUNT;
                    semaphores[nextPlayer].release();
                }
            }).start();
        }
    }

    private static int rollDice() {
        Random random = new Random();
        return random.nextInt(6) + 1; // 返回1到6之间的随机数
    }
}
